<template>
  <div class="product-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品编码">
          <el-input v-model="searchForm.productCode" placeholder="请输入商品编码" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item>
          <div class="search-buttons">
            <el-button type="primary" :loading="loading" @click="handleSearch">
              <span>查询</span>
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">新增商品</el-button>
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="商品图片" width="100">
        <template #default="{ row }">
          <el-image :src="row.imageUrl" :preview-src-list="[row.imageUrl]" preview-teleported fit="contain"
            style="width: 100%; height: 100%">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="productCode" label="商品编码" width="120" />
      <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="specifications" label="规格" width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="purchasePrice" label="进价" width="100">
        <template #default="{ row }">
          ¥{{ row.purchasePrice?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="180" />

      <el-table-column prop="sellingPrice" label="售价" width="100">
        <template #default="{ row }">
          ¥{{ row.sellingPrice?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增商品' : '编辑商品'" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" status-icon>
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="formData.productCode" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="formData.specifications" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" />
        </el-form-item>
        <el-form-item label="进价" prop="purchasePrice">
          <el-input-number v-model="formData.purchasePrice" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="售价" prop="sellingPrice">
          <el-input-number v-model="formData.sellingPrice" :precision="2" :step="0.1" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" inline-prompt active-text="启用"
            inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
            :on-success="handleUploadSuccess" :before-upload="beforeUpload">
            <template v-if="formData.imageUrl">
              <div class="image-preview-wrapper">
                <el-image ref="imageRef" :src="formData.imageUrl" class="avatar" fit="cover" />
                <div class="image-preview-actions">
                  <el-icon class="delete-icon" @click.stop="handleRemoveImage">
                    <Delete />
                  </el-icon>
                </div>
              </div>
            </template>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, toRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productApi, uploadApi } from '../../../api'

// 搜索表单
const searchForm = reactive({
  productCode: '',
  productName: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitLoading = ref(false)
const formData = reactive({
  id: null,
  productCode: '',
  productName: '',
  specifications: '',
  unit: '',
  purchasePrice: 0,
  sellingPrice: 0,
  status: 1,
  imageUrl: ''
})

// 表单验证规则
const rules = {
  productCode: [
    { required: true, message: '请输入商品编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  specifications: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  purchasePrice: [
    { required: true, message: '请输入进价', trigger: 'blur' },
    { type: 'number', min: 0, message: '进价不能小于0', trigger: 'blur' }
  ],
  sellingPrice: [
    { required: true, message: '请输入售价', trigger: 'blur' },
    { type: 'number', min: 0, message: '售价不能小于0', trigger: 'blur' }
  ]
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    // 确保使用最新的分页参数
    const params = {
      current: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }

    const res = await productApi.getList(params)
    res.data.records.forEach(item => {
      item.imageUrl = import.meta.env.VITE_API_URL + item.imageUrl
    })
    tableData.value = res.data.records || res.records || []
    total.value = parseInt(res.data.total || res.total || 0)
  } catch (error) {
    console.error('获取数据错误：', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  getTableData()
}

// 选择行
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(formData, {
      id: null,
      productCode: '',
      productName: '',
      specifications: '',
      unit: '',
      purchasePrice: 0,
      sellingPrice: 0,
      status: 1,
      imageUrl: ''
    })
  })
}

// 编辑
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  try {
    // 获取最新的商品详情
    const { data: detail } = await productApi.getDetail(row.id)
    nextTick(() => {
      if (formRef.value) {
        formRef.value.resetFields()
      }
      // 图片预览
      if (detail.imageUrl) {
        detail.imageUrl = import.meta.env.VITE_API_URL + detail.imageUrl
      }
      Object.assign(formData, detail)
      console.log(toRaw(formData), 'formData')
    })
  } catch (error) {
    dialogVisible.value = false
  }
}

// 提交表单
const handleSubmit = async () => {

  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      formData.createDate = new Date(+new Date() + 8 * 3600 * 1000).toISOString().slice(0, 19).replace('T', ' ')// 格式：YYYY-MM-DD HH:mm:ss
      try {
        if (tempFile.value) {
          const formDataUpload = new FormData()
          formDataUpload.append('file', tempFile.value)
          // 上传图片
          const res = await uploadApi.upload(formDataUpload)
          console.log(res);
          if (res.code !== 200) {
            ElMessage.error('图片上传失败')
            return
          }
          formData.imageUrl = res.data
        }
        if (dialogType.value === 'add') {
          await productApi.add(formData)
        } else {
          await productApi.update(formData)
        }
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        getTableData()
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该商品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await productApi.delete(row.id)
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      getTableData()
    } catch {
      // 错误已在拦截器中处理
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }

  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 个商品吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      await productApi.batchDelete(ids)
      ElMessage.success('删除成功')
      if (tableData.value.length === selectedRows.value.length && currentPage.value > 1) {
        currentPage.value--
      }
      getTableData()
    } catch {
      // 错误已在拦截器中处理
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1  // 重置到第一页
  getTableData()
}

// 页码改变
const handleCurrentChange = (val) => {
  console.log('页码改变：', val) // 调试用
  currentPage.value = val
  getTableData()
}
// 添加图片上传相关配置
const uploadUrl = import.meta.env.VITE_API_URL + '/upload'  // 替换为实际的上传接口地址
const tempFile = ref(null) // 用于存储临时文件
// 上传前预览
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 本地预览
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = (e) => {
    formData.imageUrl = e.target.result
  }
  //保存文件引用
  tempFile.value = file
  console.log(tempFile.value, 'tempFile');

  return false
}

// 上传成功后更新为服务器返回的URL
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    formData.imageUrl = response.data
    console.log(response.data, 'response.data');

    ElMessage.success('上传成功')
  }
}

// 删除图片
const handleRemoveImage = () => {
  ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formData.imageUrl = ''
    ElMessage.success('图片已删除')
  }).catch(() => { })
}

const imageRef = ref(null)

// 初始化
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.search-buttons .el-button {
  min-width: 80px;
  /* 设置最小宽度 */
}

.action-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-preview-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
}

.image-preview-wrapper:hover .image-preview-actions {
  opacity: 1;
}

.image-preview-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.preview-icon,
.delete-icon {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
}

.preview-icon:hover,
.delete-icon:hover {
  transform: scale(1.1);
  background: rgba(0, 0, 0, 0.7);
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>